<script setup lang='ts'>
import type { DataTableRowKey } from 'naive-ui'
import {
  NButton, NCard, NDataTable, NDynamicTags, NInput, NLayout, NLayoutContent,
  NLayoutHeader, NModal, NSelect, NSpace, useMessage,
} from 'naive-ui'
import { computed, h, ref, watch } from 'vue'
import axios from 'axios'
import { SvgIcon } from '@/components/common'
// import OutlineGeneration from '../outlineGeneration/index.vue'
import { useOpinionStore } from '@/stores/main'

const opinionStore = useOpinionStore()

// 假设每篇文章有一个唯一的ID作为键
interface Article {
  articleId: string
  articleTitle: string
  articleYear: string
  articleAuthors: string
  articleLanguage: string
  articleText: string
}
// const articles = ref([]);
const articles = ref<Article[]>([])
// 更新：标题、时间、作者、全文检索
const searchField = ref('articleTitle')
const searchOptions = ref([
  { label: '标题', value: 'articleTitle' },
  // { label: '时间', value: 'articleYear' },
  { label: '作者', value: 'articleAuthors' },
  { label: '文章全文', value: 'articleText' },
])

const showAbstractModal = ref(false)
const showOutlineModal = ref(false)
const showExtractModal = ref(false)
const showOutlineProgress = ref(false)
const showExtractProgress = ref(false)
const currentAbstract = ref('')
// const searchQuery = ref('');
const searchQuery = ref<string>('')
const checkedRowKeys = ref<DataTableRowKey[]>([])
// 大纲生成中使用的选中文章id列表
const selectedArticleIds = ref<string[]>([])
// 观点抽取中使用的选中文章id
// const selectedArticleIdToExtract = ref<string>('');

const outlineProgress = ref(0)
const extractProgress = ref(0)
const showCustomDateModal = ref(false)
const dateFilter = ref('')
const startYear = ref(null)
const endYear = ref(null)

const options = ref([
  { label: '单篇观点抽取', value: 'single' },
  { label: '多篇报告生成', value: 'multiple' },
])

// 定义一个响应式变量来存储选中的值
const selectedOption = ref('single')

// 定义文章列表正文部分是否展开
const expandedStates = ref<{ [key: string]: boolean }>({})

// 定义 columns
const columns = [
  {
    type: 'selection',
    multiple: false,
    width: '50px',
  },
  {
    key: 'detail',
    width: '100%',
    render(row: Article) {
      // 切换文章展开状态的函数
      const toggleExpand = () => {
        expandedStates.value[row.articleId] = !expandedStates.value[row.articleId]
      }
      return [
        h('div', { style: { color: 'green' } }, `${row.articleTitle}`),
        h('div', {
          style: { display: 'flex', alignItems: 'center', gap: '10px' },
        }, [
          // 仅当 articleYear 不为 null 时渲染
          row.articleYear
            ? h('div', {
              style: {
                display: 'inline-block',
                padding: '2px 8px',
                borderRadius: '10px',
                backgroundColor: '#f0f0f0',
              },
            }, `${row.articleYear}`)
            : null,
          // 仅当 articleAuthors 不为 null 时渲染
          row.articleAuthors ? h('div', { style: { color: 'grey' } }, `${row.articleAuthors}`) : null,
        ]),
        // 根据展开状态动态添加或移除 three-line-clamp 类
        h('div', {
          class: { 'three-line-clamp': !expandedStates.value[row.articleId] },
          onClick: toggleExpand,
          style: {
            cursor: 'pointer', // 点击后可以展示全文内容/显示前三行 切换
            whiteSpace: 'pre-line', // 保留换行符
          },
        }, `${row.articleText}`),
        // h('div', {}, `${row.articleId}`)
      ]
    },
  },
]

// 为每行定义一个唯一键
const rowKey = (row: Article) => row.articleId

// 处理复选框状态变化
// const handleCheck = (keys: DataTableRowKey[]) => {
//   checkedRowKeys.value = keys;
// };
// 更新选中的文章ID
const handleCheck = (checkedRowKeys: string[]) => {
  selectedArticleIds.value = checkedRowKeys
}

watch(dateFilter, (newValue) => {
  if (newValue === 'custom')
    showCustomDateModal.value = true
})

const fetchArticles = async () => {
  try {
    console.log('打印keyWord', searchQuery.value)
    const response = await axios({
      method: 'post',
      // baseURL:'http://10.129.40.245:8080',
      baseURL: 'http://127.0.0.1:8088',
      url: '/findArticleByKeyword',
      data: {
        keyWord: searchQuery.value,
        pageNo: 1,
        pageSize: 10,
      },
    })
    articles.value = response.data
  }
  catch (error) {
    console.error('Error fetching articles:', error)
    articles.value = []
  }
}

// const filteredArticles = computed(() => {
//   if (!searchQuery.value)
//     return articles.value

//   // 根据文章标题进行检索,返回符合条件文章
//   return articles.value.filter(article =>
//     article.articleTitle.includes(searchQuery.value),
//   )
// })
// 更新：标题、时间、作者、全文检索
const filteredArticles = computed(() => {
  if (!searchQuery.value)
    return articles.value

  return articles.value.filter((article) => {
    // 使用可选链 (?.) 和空值合并运算符 (??) 确保不会因为 null/undefined 而出错
    const fieldValue = article[searchField.value]?.toString() ?? ''
    return fieldValue.includes(searchQuery.value)
  })
})

const message = useMessage()

const cancelCallback = () => {
  message.success('Cancel')
}

// const submitCallback = () => {
//   message.success('Submit')
//   console.log('模态框确认生成操作');
//   // 根据需要进行操作，比如console测试
// }

const handleGenerateClick = () => {
  if (selectedOption.value === 'multiple') {
    showOutlineModal.value = true
  }
  else if (selectedOption.value === 'single') {
    // console.log(111)
    showExtractModal.value = true
    // 这里可以放置“单篇观点抽取”时的逻辑，如果没有则不执行任何操作
    // 例如，显示一个消息或执行特定逻辑
    // message.info('单篇观点抽取逻辑执行');
  }
}

// const handleOutlineSubmit = (outlineData) => {
//   console.log("hhhhh")
//   const postData = {
//     articleList: checkedRowKeys.value.map(key => {
//       const article = articles.value.find(article => article.articleId === key);
//       return {
//         articleTitle: article.articleTitle,
//         articleText: article.articleText
//       };
//     }),
//     userTitle: outlineData.reportTitle,
//     userOutline: outlineData.reportOutlines
//   };
//   console.log(postData)
//   // 在这里发送POST请求
//   axios.post('您的接口URL', postData)
//     .then(response => {
//       // 处理成功响应
//       console.log('Success:', response);
//     })
//     .catch(error => {
//       // 处理错误
//       console.error('Error:', error);
//     });
// };

// 实现平滑增加进度条的效果
// const smoothProgress = (start: number, end: number, duration: number) => {
//   const increment = (end - start) / (duration / 10)
//   let currentProgress = start

//   const interval = setInterval(() => {
//     currentProgress += increment
//     outlineProgress.value = Math.min(currentProgress, end)

//     if (currentProgress >= end)
//       clearInterval(interval)
//   }, 10)
// }

// 观点抽取模态框相关
// 用户自定义的抽取关键词数组初始化
const extractTags = ref([])

const cancelExtract = () => {
  message.success('Cancel')
}

const submitExtract = async () => {
  // 关闭观点抽取模态框
  showExtractModal.value = false
  // 显示进度条
  showExtractProgress.value = true
  // 设置进度条的当前进度为10%
  // extractProgress.value = 10
  // 过滤选中的文章，基于过滤后的文章列表（find适用于单一匹配项，filter适用于多个匹配项）
  const selectedArticleToExtract = filteredArticles.value.filter(article => selectedArticleIds.value.includes(article.articleId))
  // const selectedArticleToExtract = filteredArticles.value.find(article => article.articleId === selectedArticleIdToExtract.value);

  // 设置进度条的当前进度为30%
  // extractProgress.value = 30

  // 准备要发送的文章内容
  const postData = {
    // content: selectedArticleToExtract ? selectedArticleToExtract.articleText : ''
    content: selectedArticleToExtract.map(article => article.articleText).join('\n\n'),
    topics: extractTags.value,
    // content: selectedArticleToExtract.map(article => article.articleText)
  }

  // 设置 HTTP 请求的头信息，指定内容类型为 JSON
  const config = {
    headers: {
      'Content-Type': 'application/json',
    },
  }

  // 发送POST请求
  try {
    console.log(postData)
    const response = await axios.post('http://127.0.0.1:8088/extractOpinion', postData, config)
    opinionStore.setOpinionResponse(response.data)
    // 设置进度条的当前进度为70%
    // extractProgress.value = 70
    // const response = await axios.post('http://10.112.203.120:1133/extraction', postData, config);
    // 控制台输出成功提交数据的消息和服务器的响应
    // console.log('Data for Extract submitted successfully:', response.data)

    // 设置进度条的当前进度为100%
    // extractProgress.value = 100
    // 显示进度条
    showExtractProgress.value = false
  }
  // try {
  //   console.log(postData);

  // }
  catch (error) {
    console.error('Submit Error:', error)
    console.error('Error submitting data:', error)
    // 错误处理...
  }
}

// 大纲模态框相关

const inputCount = ref(3) // 默认输入框数量为三个
const reportOutlines = ref(new Array(inputCount.value).fill(''))
// const reportOutlines = ref<string[]>([]);
const reportTitle = ref('')

const submitCallback = async () => {
  // 关闭大纲模态框
  showOutlineModal.value = false
  // 显示进度条
  showOutlineProgress.value = true
  // 设置进度条的当前进度为10%
  // outlineProgress.value = 10
  // smoothProgress(0, 10, 2000)
  // 过滤选中的文章，基于过滤后的文章列表
  const selectedArticles = filteredArticles.value.filter(article => selectedArticleIds.value.includes(article.articleId))
  // 设置进度条的当前进度为30%
  // outlineProgress.value = 30
  // smoothProgress(10, 30, 2000)
  // 准备要发送的数据
  const postData = {
    doc_list: selectedArticles.map(article => ({
      doc_title: article.articleTitle,
      doc_content: article.articleText,
    })),
    user_title: reportTitle.value,
    user_outline: reportOutlines.value,
    user_keywords: '核武器、核态势、全球核武器发展、中国、美国、朝鲜、俄罗斯、中美',
  }

  // 设置 HTTP 请求的头信息，指定内容类型为 JSON
  const config = {
    headers: {
      'Content-Type': 'application/json',
    },
  }

  // 发送POST请求
  try {
    console.log(postData)
    // const response = await axios.post('/api/endpoint', postData);
    // console.log('Submit Success:', response);
    const response = await axios.post('http://127.0.0.1:8088/generateReport', postData, config)
    // 设置进度条的当前进度为70%
    // outlineProgress.value = 70
    // smoothProgress(30, 70, 5000)
    // const response = await axios.post('http://localhost:20618/multi_doc_generate', postData, config);
    // 控制台输出成功提交数据的消息和服务器的响应
    console.log('Data submitted successfully:', response.data)
    // 准备 PDF 生成的数据和请求
    const postData1 = {
      text: response.data,
      filename: reportTitle.value,
    }
    const generate_url = 'http://10.112.203.120:8094/generate-pdf'
    const pdfResponse = await axios.post(generate_url, postData1, {
      responseType: 'blob', // 确保处理响应为Blob类型
      headers: {
        'Content-Type': 'application/json',
      },
    })
    // 输出生成 PDF 的响应
    console.log(pdfResponse)
    // 如果 PDF 响应包含数据，则创建一个 Blob 对象，并用其创建一个 URL。
    if (pdfResponse.data) {
      const url = window.URL.createObjectURL(new Blob([pdfResponse.data], { type: 'application/pdf' }))
      // 创建一个 HTML 锚点 (<a>) 元素，设置其 href 为 Blob URL 并设置下载属性
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `${reportTitle.value}.pdf`) // 设置下载文件名
      document.body.appendChild(link)
      // 触发点击事件以启动下载。
      link.click()

      // 延迟清理
      setTimeout(() => {
        window.URL.revokeObjectURL(url)
        document.body.removeChild(link) // 清除创建的链接
      }, 100) // 延迟100毫秒确保文件下载动作已触发
    }
    // outlineProgress.value = 100
    // smoothProgress(70, 100, 2000)
    showOutlineProgress.value = false
  }
  catch (error) {
    console.error('Submit Error:', error)
    console.error('Error submitting data:', error)
    // 错误处理...
  }
}

// 减少大纲模态框中输入框个数
function decreaseInputCount() {
  if (inputCount.value > 1)
    inputCount.value--
}
// 增加大纲模态框中输入框个数
function increaseInputCount() {
  inputCount.value++
}
watch(inputCount, (newCount, oldCount) => {
  if (newCount > oldCount) {
    for (let i = oldCount; i < newCount; i++)
      reportOutlines.value.push('')
  }
  else {
    reportOutlines.value = reportOutlines.value.slice(0, newCount)
  }
})

watch(reportOutlines, (newVal) => {
  console.log('reportOutlines changed:', newVal)
})
// 用户输入大纲内容换序
function moveUp(index) {
  if (index > 0) {
    [reportOutlines.value[index], reportOutlines.value[index - 1]]
      = [reportOutlines.value[index - 1], reportOutlines.value[index]]
  }
}

function moveDown(index) {
  if (index < reportOutlines.value.length - 1) {
    [reportOutlines.value[index], reportOutlines.value[index + 1]]
      = [reportOutlines.value[index + 1], reportOutlines.value[index]]
  }
}
</script>

<template>
  <NLayout>
    <!-- 搜索框 -->
    <NLayoutHeader>
      <NCard>
        <div class="flex items-center justify-between space-x-2">
          <!-- 更新：标题、时间、作者、全文检索 -->
          <!-- 添加选择器来选择搜索字段 -->
          <NSelect
            v-model:value="searchField" :options="searchOptions" class="flex-grow-0 flex-shrink-0"
            style="flex-basis: 15%; min-width: 0;"
          />
          <NInput
            v-model:value="searchQuery" placeholder="请输入关键词" class="flex-grow-0 flex-shrink-0"
            style="flex-basis: 70%; min-width: 0;"
          />
          <!-- <NInput v-model:value="searchQuery" placeholder="请输入关键词" class="input-with-select" /> -->
          <NButton type="primary" @click="fetchArticles">
            <template #icon>
              <SvgIcon icon="ri:search-line" />
            </template>
          </NButton>
          <NButton type="primary" @click="handleGenerateClick">
            <template #icon>
              <!-- SvgIcon或其他图标 -->
              <a>生成</a>
            </template>
          </NButton>
        </div>
      </NCard>
    </NLayoutHeader>
    <NLayout has-sider>
      <!-- <NLayoutSider width="20%">
        <NCard>
          时间筛选
          <NRadioGroup v-model="dateFilter" name="time">
            <NSpace vertical>
              <NRadio label="all">时间不限</NRadio>
              <NRadio label="2024">2024年以来</NRadio>
              <NRadio label="2022">2022年以来</NRadio>
              <NRadio label="2020">2020年以来</NRadio>
              <NRadio label="custom">自定义时间范围</NRadio>
            </NSpace>
          </NRadioGroup>

          <NModal v-model:show="showCustomDateModal" title="选择时间范围">
            <NSpace vertical>
              <NInputNumber v-model:value="startYear" placeholder="开始年份" min="1900" max="2099" />
              <NInputNumber v-model:value="endYear" placeholder="结束年份" min="1900" max="2099" />
            </NSpace>
          </NModal>
        </NCard>
        <NCard>
          排序选择
          <NRadioGroup>
            <NSpace vertical>
              <NRadio label="default">默认排序</NRadio>
              <NRadio label="asc">时间升序</NRadio>
              <NRadio label="desc">时间降序</NRadio>
            </NSpace>
          </NRadioGroup>
        </NCard>
        <NCard>
          语言选择
          <NRadioGroup>
            <NSpace vertical>
              <NRadio label="all">所有语言</NRadio>
              <NRadio label="cn">中文</NRadio>
              <NRadio label="en">英文</NRadio>
            </NSpace>
          </NRadioGroup>
        </NCard>
      </NLayoutSider> -->

      <NLayoutContent>
        <NCard>
          <!-- <NModal v-model:show="showOutlineModal" preset="dialog" title="报告大纲生成" positive-text="确认生成" negative-text="取消"
            @positive-click="submitCallback" @negative-click="cancelCallback" @submitOutline="handleOutlineSubmit"
            style="width: 30%">
            <OutlineGeneration @closeModal="showOutlineModal = false" />
          </NModal> -->

          <!-- 确认观点抽取文章的模态框 -->
          <!-- <NModal v-model:show="showExtractModal" preset="dialog" title="观点抽取确认" content="确认选择该篇文章进行观点抽取吗？"
            positive-text="确认抽取" negative-text="取消" style="width: 30%" @positive-click="submitExtract"
            @negative-click="cancelExtract">
          </NModal> -->
          <NModal
            v-model:show="showExtractModal" preset="dialog" title="观点抽取" positive-text="确认抽取" negative-text="取消"
            style="width: 30%" @positive-click="submitExtract" @negative-click="cancelExtract"
          >
            <NCard>
              <NSpace vertical>
                <div>请输入抽取关键词</div>
                <NSpace>
                  <NDynamicTags v-model:value="extractTags" :max="10" />
                </NSpace>
              </NSpace>
            </NCard>
          </NModal>
          <!-- 确认观点抽取文章后的模态框 -->
          <NModal v-model:show="showExtractProgress" preset="dialog" title="正在进行观点抽取" style="width: 30%">
            <NSpace vertical>
              <!-- <NProgress type="dashboard" gap-position="bottom" :percentage="extractProgress" /> -->
              <div>预计抽取时间为: 30秒, 请耐心等待...</div>
            </NSpace>
          </NModal>

          <!-- 提交报告标题及大纲内容后的模态框 -->
          <NModal v-model:show="showOutlineProgress" preset="dialog" title="正在生成报告" style="width: 30%">
            <NSpace vertical>
              <!-- <NProgress type="line" :percentage="outlineProgress" :indicator-placement="'inside'" processing/> -->
              <div>预计生成时间为: 5分钟, 请耐心等待...</div>
            </NSpace>
          </NModal>

          <!-- 编辑报告标题及大纲内容的模态框 -->
          <NModal
            v-model:show="showOutlineModal" preset="dialog" title="报告大纲生成" positive-text="确认生成" negative-text="取消"
            style="width: 30%" @positive-click="submitCallback" @negative-click="cancelCallback"
          >
            <!-- <OutlineGeneration @closeModal="showOutlineModal = false" /> -->
            <NCard>
              <NSpace vertical>
                <div>请输入报告标题</div>
                <NInput v-model:value="reportTitle" type="text" placeholder="请输入报告标题" />
                <NSpace>
                  <div>可修改增删大纲</div>
                  <!-- “减”按钮 -->
                  <NButton @click="decreaseInputCount">
                    -
                  </NButton>
                  <!-- “加”按钮 -->
                  <NButton @click="increaseInputCount">
                    +
                  </NButton>
                </NSpace>

                <!-- 使用 v-for 根据 inputCount 动态生成输入框 -->
                <!-- <NInput
                  v-for="index in inputCount" :key="index" v-model:value="reportOutlines[index - 1]" type="text"
                  placeholder="请输入报告大纲内容" clearable
                /> -->
                <div v-for="(outline, index) in reportOutlines" :key="index" class="input-group">
                  <NInput v-model:value="reportOutlines[index]" type="text" placeholder="请输入报告大纲内容" clearable />
                  <!-- 用户输入大纲内容换序 -->
                  <NButton :disabled="index === 0" @click="moveUp(index)">
                    ↑
                  </NButton>
                  <NButton :disabled="index === reportOutlines.length - 1" @click="moveDown(index)">
                    ↓
                  </NButton>
                </div>
              </NSpace>
            </NCard>
          </NModal>
        </NCard>

        <!-- 文章列表 -->
        <!-- 文章列表表格 -->
        <NCard>
          <!-- <div>共检索出6篇文章</div> -->

          <NDataTable
            :columns="columns" :data="filteredArticles" :row-key="rowKey"
            @update:checked-row-keys="handleCheck"
          />
        </NCard>
      </NLayoutContent>
    </NLayout>
  </NLayout>
  <!-- 摘要弹窗 -->
  <NModal v-model:show="showAbstractModal" title="文章摘要" :width="600">
    <NCard style="width: 600px" title="文章摘要" :bordered="false" size="huge" role="dialog" aria-modal="true">
      <p>{{ currentAbstract }}</p>
      <template #footer>
        <NSpace>
          <NButton type="primary" @click="showAbstractModal = false">
            关闭
          </NButton>
        </NSpace>
      </template>
    </NCard>
  </NModal>
</template>

<style>
/* 限制文本显示为三行 */
.three-line-clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
